package com.toman.ui.work.workplan;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseDayPlanEntity;
import com.toman.JavaBean.DeviceHouseDayPlanMappingEntity;
import com.toman.R;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.camera.Camera;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class SubmitPlanAddActivity extends ToolBarActivity {
    Camera camera;

    Dialog dialog;


    DeviceHouseDayPlanMappingEntity bean = new DeviceHouseDayPlanMappingEntity();
    DeviceHouseDayPlanEntity beanParent = new DeviceHouseDayPlanEntity();
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.rl_dep)
    RelativeLayout rlDep;
    @BindView(R.id.tv_beltline_child)
    TextView tvBeltlineChild;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.tv_planoutput)
    TextView tvPlanoutput;
    @BindView(R.id.et_completed_count)
    ClearEditText etCompletedCount;
    @BindView(R.id.et_qualified_count)
    ClearEditText etQualifiedCount;
    @BindView(R.id.et_waste_count)
    ClearEditText etWasteCount;
    @BindView(R.id.et_scrapped_count)
    ClearEditText etScrappedCount;
    @BindView(R.id.et_remake_count)
    ClearEditText etRemakeCount;
    @BindView(R.id.et_reuse_count)
    ClearEditText etReuseCount;
    @BindView(R.id.tv_order_remark_name)
    TextView tvOrderRemarkName;
    @BindView(R.id.et_order_remark)
    EditText etOrderRemark;
    @BindView(R.id.ll)
    LinearLayout ll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_plan);
        ButterKnife.bind(this);
        initIntent();
        initView();
    }

    private void initView() {
        baseEnum = BaseEnum.WORKSHOPSUBMIT;
        initToolBar(baseEnum.add());
        camera = ViewUtil.createPhoto("请提供相关截图或照片", camera, this, ll);
        if (getIntent().getSerializableExtra("bean") != null) {
            String[] item = new String[]{beanParent.getDepartmentName() + "", bean.getBeltlineName(), beanParent.getDay(), bean.getPlanOutput() + ""};//直接初始化
            ViewUtil.setText(item, tvDep, tvBeltlineChild, tvDay, tvPlanoutput);
            ViewUtil.unclick(tvDep, tvBeltlineChild, tvDep);
        }

    }

    private void initIntent() {
        if (getIntent().getSerializableExtra("bean") != null) {
            bean = (DeviceHouseDayPlanMappingEntity) getIntent().getSerializableExtra("bean");
            beanParent = (DeviceHouseDayPlanEntity) getIntent().getSerializableExtra("beanParent");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }


    public void add() {
        String[] item = new String[]{"完工数量", "合格数量", "报废数量", "料废数量", "返工数量", "回用数量"};//直接初始化

        if (ViewUtil.isNull(this, item, etCompletedCount, etQualifiedCount, etScrappedCount, etWasteCount, etRemakeCount, etReuseCount)
                ) {
            return;
        }
        if (ViewUtil.compareString(this, item, etCompletedCount, etQualifiedCount)
                ) {
            return;
        }

        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");

        List<String> list = camera.getCompressUrl();
        List<File> files = new ArrayList<>();
        for (String path : list) {
            File file = new File(path);
            files.add(file);
        }
        OkHttpUtils
                .post(NewBaseUrl.devicehouseproductreport_save)
                .headers("token", token)
                .headers("Content-Type", "multipart/form-data")
                .addFileParams("file", files)
                .params("departmentId", beanParent.getDepartmentId() + "")
                .params("beltlineId", bean.getBeltlineId() + "")
                .params("day", beanParent.getDay() + "")
                .params("finishCount", etCompletedCount.getText().toString())
                .params("qualifiedCount", etQualifiedCount.getText().toString())
                .params("brokenCount", etScrappedCount.getText().toString())
                .params("wasteCount", etWasteCount.getText().toString())
                .params("remadeCount", etRemakeCount.getText().toString())
                .params("reuseCount", etReuseCount.getText().toString())
                .params("description", etOrderRemark.getText().toString())

                .execute(new StringCallback() {
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        Toast.makeText(getApplicationContext(), "请检查您的网络连接!", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }

                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            dialog.dismiss();
                            SPUtils.put(getApplicationContext(), BaseEnum.WORKSHOPDAYPLAN.update(), true);

                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }
                        dialog.dismiss();

                    }
                });

    }


    @OnClick({R.id.tv_dep, R.id.tv_beltline_child, R.id.tv_day})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_dep:
                DialogUtils.showDialog(this, NetworkEnum.DEP, mCompanyId, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        beanParent.setDepartmentId(Long.valueOf(bean1.getID()));
                        tvDep.setText(bean1.getName());
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.tv_beltline_child:
                DialogUtils.showDialog(this, NetworkEnum.BELTLINE, mCompanyId, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        beanParent.setDepartmentId(Long.valueOf(bean1.getID()));
                        tvDep.setText(bean1.getName());
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.tv_day:
                ViewUtil.getDate(this,tvDay);
                break;
        }
    }
}
